package com.jfinal.cli.common.plugin.swagger.util;

import com.jfinal.kit.PropKit;

/**
 * @author: lbq
 * @email: 526509994@qq.com
 * @date: 2019/4/19
 */
public class JsonUtil {

    /**
     * 格式化
     *
     * @param url retJson.properties中配置的url
     */
    public static String formatJson(String url) {
        String jsonStr = PropKit.use("swaggerJson.properties").get(url);
        if (null == jsonStr || "".equals(jsonStr))
            return "";
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        boolean isInQuotationMarks = false;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '"':
                    if (last != '\\') {
                        isInQuotationMarks = !isInQuotationMarks;
                    }
                    sb.append(current);
                    break;
                case '{':
                case '[':
                    sb.append(current);
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent++;
                        addIndentBlank(sb, indent);
                    }
                    break;
                case '}':
                case ']':
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent--;
                        addIndentBlank(sb, indent);
                    }
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\' && !isInQuotationMarks) {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }

        return sb.toString();
    }

    /**
     * 添加space
     *
     * @param sb
     * @param indent
     * @author lizhgb
     * @Date 2015-10-14 上午10:38:04
     */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }

    public static void main(String[] args) {
        String json = "{ \"meetEnd\": { \"reason\": \"Can not Find Meet By MeetId[1055]\", \"code\": -1 }, \"state\": \"ok\", \"meetDelete\": {}, \"timestamp\": \"2019-04-19 15:22:20\" }\n";
        System.out.println(formatJson(json));
    }


}
